package org.rain.core.querygen.support;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.rain.common.util.Strs;
import org.rain.core.querygen.AbsQueryCondition;
import org.rain.core.querygen.token.Token;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * created by yangtong on 2025/4/6 下午10:36
 * <p>
 * in匹配 age_in=1,2,3 -> age in(1,2,3)
 */
@Component
public class InQueryCondition extends AbsQueryCondition implements Ordered {
    @Override
    public Boolean isMatch(Token token) {
        return Strs.isNotEmpty(token.getValue()) && token.getKey().endsWith("_in");
    }

    @Override
    public <T> QueryWrapper<T> genQueryWrapper(QueryWrapper<T> queryWrapper, Token token) {
        //去除掉key后面的"_in"
        String realKey = token.getKey().substring(0, token.getKey().length() - 3);
        token.setKey(realKey);
        return positiveOrNegate(queryWrapper, token);
    }

    @Override
    protected <T> QueryWrapper<T> positive(QueryWrapper<T> queryWrapper, Token token) {
        List<String> values = Arrays.stream(token.getValue().split(",")).filter(Objects::nonNull).toList();
        if (values.isEmpty()) {
            values = List.of("-1");
        }
        return queryWrapper.in(Strs.toUnderline(token.getKey()), values);
    }

    @Override
    protected <T> QueryWrapper<T> negate(QueryWrapper<T> queryWrapper, Token token) {
        return queryWrapper.not(w -> positive(w, token));
    }

    @Override
    public int getOrder() {
        return Integer.MIN_VALUE + 1;
    }
}
